<template>
  <div ref="echartsRef" class="chart-container"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption, PieSeriesOption } from 'echarts';

interface EchartsDataItem {
  name: string;
  value: number;
  itemStyle: {
    color: string;
  };
  clickData?: any;
}

interface Props {
  id?: string;
  title?: string;
  echartsData: EchartsDataItem[] | undefined;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: 'thirdGeneralClick', params: any): void;
}>();

const echartsRef = ref<HTMLElement | null>(null);
const chartInstance = ref<ECharts | null>(null);
let resizeObserver: ResizeObserver | null = null;

// 初始化图表
const initChart = () => {
  if (!echartsRef.value) return;

  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  chartInstance.value = echarts.init(echartsRef.value);
  updateChart();
  setupResizeObserver();
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance.value || !props.echartsData?.length) return;

  const options = getChartOptions(props.echartsData);
  chartInstance.value.setOption(options);
  setupChartEvents();
};

// 获取图表配置
const getChartOptions = (data: EchartsDataItem[]): EChartsOption => {
  const colors = data.map((item) => item.itemStyle.color);
  const seriesData = data.map((item) => ({
    name: item.name,
    value: item.value,
    clickData: item.clickData
  }));

  return {
    color: colors,
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: getLegendConfig(),
    series: [getPieSeriesConfig(props.title, seriesData)]
  };
};

// 获取图例配置
const getLegendConfig = () => ({
  orient: 'horizontal',
  x: 'center',
  bottom: 0,
  itemGap: 10,
  itemWidth: 10,
  itemHeight: 10,
  textStyle: {
    color: '#fff',
    fontSize: 12
  }
});

// 获取饼图系列配置
const getPieSeriesConfig = (
  name: string | undefined,
  data: Array<{
    name: string;
    value: number;
  }>
): PieSeriesOption => ({
  name,
  type: 'pie',
  radius: '50%',
  label: {
    formatter: '{d}%',
    textStyle: {
      fontSize: 16
    }
  },
  data,
  emphasis: {
    itemStyle: {
      shadowBlur: 10,
      shadowOffsetX: 0,
      shadowColor: 'rgba(0, 0, 0, 0.5)'
    }
  }
});

// 设置图表事件
const setupChartEvents = () => {
  if (!chartInstance.value) return;

  chartInstance.value.off('click');
  chartInstance.value.on('click', (params) => {
    emit('thirdGeneralClick', params);
  });
};

// 设置响应式观察
const setupResizeObserver = () => {
  if (!echartsRef.value) return;

  resizeObserver = new ResizeObserver(() => {
    chartInstance.value?.resize();
  });
  resizeObserver.observe(echartsRef.value);
};

// 清理资源
const cleanup = () => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }

  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }

  window.removeEventListener('resize', handleResize);
};

const handleResize = () => {
  chartInstance.value?.resize();
};

// 生命周期钩子
onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(cleanup);

// 监听数据变化
watch(
  () => [props.echartsData, props.title],
  (newVal) => {
    updateChart();
  },
  { deep: true }
);
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
